package view;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import entity.User;
import main.Main;
import util.Constants;
import util.Validator;

public class ChangePasswordJPanel extends JPanel {
	private static final long serialVersionUID = -7842992699540714629L;

	public ChangePasswordJPanel(){
        setLayout(null);
        setBorder(BorderFactory.createTitledBorder("修改密码"));
        initUI();
	}
	
	private void initUI(){
		JLabel lab1 = new JLabel("用户名",SwingConstants.RIGHT);
		lab1.setFont(Constants.font);
		lab1.setBounds(300, 30, 60, 30);
		
		JTextField lab1input = new JTextField(Main.user.name);
		lab1input.setBounds(365, 30, 120, 30);
		lab1input.setEnabled(false);
        
        JLabel lab2 = new JLabel("新密码",SwingConstants.RIGHT);
        lab2.setFont(Constants.font);
        lab2.setBounds(300, 90, 60, 30);
        
        JPasswordField newPwd = new JPasswordField();
        newPwd.setBounds(365, 90, 120, 30);
        
		JLabel lab3 = new JLabel("确认密码",SwingConstants.RIGHT);
		lab3.setFont(Constants.font);
		lab3.setBounds(300, 150, 60, 30);
		
		JPasswordField newPwd2 = new JPasswordField();
		newPwd2.setBounds(365, 150, 120, 30);
        
		JButton btn = new JButton("保存");
		btn.setBounds(365, 210, 60, 30);
		btn.setFont(Constants.font);
		btn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				String newPwdStr = new String(newPwd.getPassword());
				String newPwd2Str = new String(newPwd2.getPassword());
				
				if (Validator.isEmpty(newPwdStr)) {
					JOptionPane.showMessageDialog(null, "请输入新密码！");
					return;
				}
				
				if (Validator.isEmpty(newPwd2Str)) {
					JOptionPane.showMessageDialog(null, "请输入确认密码！");
					return;
				} 
				
				if (!newPwd2Str.equals(newPwdStr)) {
					JOptionPane.showMessageDialog(null, "新密码与确认密码不一致！");
					return;
				} 

				boolean result = false;
				User user = Main.user;
				String oldPwd = user.pwd;
				user.pwd = newPwdStr;
				result = user.updatePwd();
				if (result) {
					JOptionPane.showMessageDialog(null, "操作成功！");
				}else{
					user.pwd = oldPwd;
					JOptionPane.showMessageDialog(null, "操作失败！");
				}
			}
				
		});
		
		add(lab1);
		add(lab1input);
		add(lab2);
		add(newPwd);
		add(lab3);
		add(newPwd2);
		add(btn);
	}
}
